package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.redis.service.IStatisticsVORedisService;
import cn.wolfcode.wolf2w.redis.vo.StatisticsVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.util.DateUtil;
import cn.wolfcode.wolf2w.util.RedisKeysStandard;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class StatisticsVORedisServiceImpl implements IStatisticsVORedisService {
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ITravelService travelService;
    @Override
    public void addViewnum(String sid, int num) {
        // 获取redis中vo对象
        StatisticsVO statisticsVO = this.getStatisticsVOInRedis(sid);
        // 进行阅读数加1
        statisticsVO.setViewnum(statisticsVO.getViewnum() + num);
        // 更新到redis中
        this.setStatisticsVOInRedis(statisticsVO);
    }

    @Override
    public StatisticsVO getStatisticsVOInRedis(String sid) {
        String key = RedisKeysStandard.STATISTICS_VO_OBJECT.addKeyMessage(sid);
        // 创建vo对象（接收数据）
        StatisticsVO statisticsVO = new StatisticsVO();
        if (!template.hasKey(key)) {
            // redis中不存在该key的处理方法
            // 查询数据库数据添加到redis缓存中
            Strategy strategy = strategyService.get(sid);
            BeanUtils.copyProperties(strategy, statisticsVO);
            statisticsVO.setStrategyId(strategy.getId());
            // 缓存到redis中
            template.opsForValue().set(key, JSON.toJSONString(statisticsVO));
        }else {
            // redis中存在该key的处理方法
            // 拿出该key在redis中的值
            String value = template.opsForValue().get(key);
            //转化为statisticsVO对象
            statisticsVO = JSON.parseObject(value, StatisticsVO.class);
        }
        return statisticsVO;
    }

    @Override
    public StatisticsVO getStatisticsVOByTravel(String tid) {
        String key = RedisKeysStandard.STATISTICS_VO_OBJECT.addKeyMessage(tid);
        // 创建vo对象（接收数据）
        StatisticsVO statisticsVO = new StatisticsVO();
        if (!template.hasKey(key)) {
            // redis中不存在该key的处理方法
            // 查询数据库数据添加到redis缓存中
            Travel travel = travelService.get(tid);
            BeanUtils.copyProperties(travel, statisticsVO);
            statisticsVO.setStrategyId(travel.getId());
            // 缓存到redis中
            template.opsForValue().set(key, JSON.toJSONString(statisticsVO));
        }else {
            // redis中存在该key的处理方法
            // 拿出该key在redis中的值
            String value = template.opsForValue().get(key);
            //转化为statisticsVO对象
            statisticsVO = JSON.parseObject(value, StatisticsVO.class);
        }
        return statisticsVO;
    }

    @Override
    public void setStatisticsVOInRedis(StatisticsVO vo) {
        String key = RedisKeysStandard.STATISTICS_VO_OBJECT.addKeyMessage(vo.getStrategyId());
        template.opsForValue().set(key,JSON.toJSONString(vo));
    }

    @Override
    public void addReplynum(String sid, int num) {
        // 获取redis中co对象
        StatisticsVO vo = this.getStatisticsVOInRedis(sid);
        // 设置回复数
        vo.setReplynum(vo.getReplynum() + num);
        // 更新到redis中
        this.setStatisticsVOInRedis(vo);
    }

    @Override
    public boolean isAddFavor(String sid, String uid) {
        // 生成收藏的key
        String favorKey = RedisKeysStandard.USER_FAVOR_STRATEGIES.addKeyMessage(uid);
        // 是否存在该key的处理

        List<String> list = new ArrayList<>();
        if (template.hasKey(favorKey)) {
            String uList = template.opsForValue().get(favorKey);
            list = JSON.parseArray(uList, String.class);
        }
        StatisticsVO vo = this.getStatisticsVOInRedis(sid);
        // 判断sid是否存在list中
        if (list.contains(sid)) { //存在 执行取消收藏操作
            vo.setFavornum(vo.getFavornum() - 1);
            list.remove(sid);
        }else {//不存在 执行收藏操作
            vo.setFavornum(vo.getFavornum() + 1);
            list.add(sid);
        }
        // 更新到redis中
        template.opsForValue().set(favorKey,JSON.toJSONString(list));
        this.setStatisticsVOInRedis(vo);
        return list.contains(sid);
    }

    @Override
    public List<String> getFavorSids(String userId) {
        String key = RedisKeysStandard.USER_FAVOR_STRATEGIES.addKeyMessage(userId);
        List<String> list = new ArrayList<>();
        if (template.hasKey(key)) {
            String uList = template.opsForValue().get(key);
            list = JSON.parseArray(uList, String.class);
        }

        return list;
    }

    @Override
    public boolean strategyThumbup(String sid, String uid) {
        // 生成key存到redis中
        String key = RedisKeysStandard.STRATEGY_THUMB.addKeyMessage(uid,sid);
        if (template.hasKey(key)) {
            return false;
        }
        // 设置时间（从点赞到今天的23:59：59结束）
        Date now = new Date();
        Date end = DateUtil.getEndDate(now);
        long time = DateUtil.getDateBetween(end, now);
        template.opsForValue().set(key, "1", time, TimeUnit.SECONDS);
        StatisticsVO vo = this.getStatisticsVOInRedis(sid);
        vo.setThumbsupnum(vo.getThumbsupnum() + 1);
        this.setStatisticsVOInRedis(vo);
        return true;
    }

    @Override
    public List<StatisticsVO> getAllStatisticsVO(String pattern) {
        String voKey = RedisKeysStandard.STATISTICS_VO_OBJECT.addKeyMessage(pattern);
        List<StatisticsVO> list = new ArrayList<>();
        Set<String> keys = template.keys(voKey);
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                String uList = template.opsForValue().get(key);
                list.add(JSON.parseObject(uList,StatisticsVO.class));
            }
        }
        return list;
    }

    @Override
    public boolean isExistSid(String sid) {
        String key = RedisKeysStandard.STATISTICS_VO_OBJECT.addKeyMessage(sid);
        return template.hasKey(key);
    }

    @Override
    public boolean thumbUp(String tid, String uid) {
        // 生成key存到redis中
        String key = RedisKeysStandard.TRAVEL_THUMB.addKeyMessage(uid,tid);
        if (template.hasKey(key)) {
            return false;
        }
        // 设置时间（从点赞到今天的23:59：59结束）
        Date now = new Date();
        Date end = DateUtil.getEndDate(now);
        long time = DateUtil.getDateBetween(end, now);
        template.opsForValue().set(key, "1", time, TimeUnit.SECONDS);
        StatisticsVO vo = this.getStatisticsVOInRedis(tid);
        vo.setThumbsupnum(vo.getThumbsupnum() + 1);
        this.setStatisticsVOInRedis(vo);
        return true;
    }
}
